package main.controller;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import main.entity.ReplyVO;
import main.service.ReplyService;
import main.utils.UtilPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/reply")
public class ReplyCtrl extends BaseCtrl<ReplyVO> {

	@Autowired
	private ReplyService replyService;
	
	@RequestMapping("/pub.do")
	public String createReply(@ModelAttribute ReplyVO replyVO){
		replyVO.setReply_time(UtilPackage.getCurrentTime());
		Integer threads_ID = replyVO.getThreads_ID();
		Integer replyID = getIBaseService().save(replyVO);
		if (replyID!=null) {
			return "redirect:/threads/"+threads_ID+"/read.do";
		} else {
			return "error";
		}
	}
	
	@RequestMapping("/{replyID}/read.do")
	public ModelAndView getByID(@PathVariable("replyID") Integer replyID){
		ReplyVO replyVO = getIBaseService().getByID(ReplyVO.class ,replyID);
		ModelAndView mdv = new ModelAndView();
//		request.setAttribute("replyVO", replyVO);
//		setTargetURL("/reply/"+replyID);
		mdv.addObject("replyVO", replyVO);
		mdv.setViewName("/"+replyID);
		return mdv;
	}
	
//	@RequestMapping("/getByThreadsID/{threadsID}")
	@ResponseBody
	public List<ReplyVO> getByThreadsID(Integer threadsID){
		List<ReplyVO> replysByThreads = replyService.getReplyByThreadsID(threadsID);
//		request.setAttribute("replysByThreads", replysByThreads);
		return replysByThreads;
	}
	
	@RequestMapping("/autoSave.do")
	@ResponseBody
	public Map<String, Object> autoSave(@ModelAttribute ReplyVO replyVO){
		Map<String, Object>resMap = new HashMap<String, Object>();
		
		Serializable rID = replyVO.getReply_ID();
		ReplyVO replyVO2 = replyService.getByID( ReplyVO.class, rID);
		
		if ( replyVO2 != null ) {
			Integer reply_ID = replyVO2.getReply_ID();
			getIBaseService().update(replyVO);
			resMap.put("message", "update successfully");
			resMap.put("replyID", reply_ID);
		} else {
			Integer replyID = getIBaseService().save(replyVO);
			resMap.put("message", "save successfully");
			resMap.put("replyID", replyID);
		}
		return resMap;
	}
	
}
